package com.jeasonzhao.model;

import com.jeasonzhao.commons.utils.Algorithms;
import com.jeasonzhao.commons.basic.IntegerPair;

public class ObjectBuilder
{
    private Object obj = null;
    private MappedInformation map = null;
    public ObjectBuilder(Class<?> cls)
        throws ModelException
    {
        obj=ModelHelper.getInstance().constructorNewInstance(cls);
        map = ModelHelper.getInstance().getMappedInformation(cls);

    }
    public ObjectBuilder set(ObjectBuilderIterator it)
        throws ModelException
    {
        if(null!=it)
        {
            for(MappedFieldItem item: map.getMappedItems())
            {
                Object value=it.valueOf(item.getName());
                this.set(item.getName(),value);
            }
        }
        return this;
    }
    public ObjectBuilder set(String name,Object value)
        throws ModelException
    {
        if(null!=map && null!=obj && Algorithms.notEmpty(name))
        {
          MappedFieldItem item=  map.getFieldMap(name);
          if(null!=item)
          {
              if(IntegerPair.class.isAssignableFrom(item.getType()) && null != value)
              {
                  value = IntegerPair.findConstant(item.getType(),value.toString(),null);
              }
              else if(null!=value)
              {
                  value = Algorithms.castValueSafe(item.getType(),value);
              }
              item.setValue(obj,value);
          }
        }
        return this;
    }
    public Object get()
    {
        return obj;
    }
}
